package client;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


public class Register{

    
private Properties prop;


public Register(){	
	this.prop = new Properties();
}


/**
 * This method inserts a file(backup file) on register
 * @param filename The name of the file(backup file)
 * @param offset The offset of the file(backup file)
 */
public void insert(String filename, long offset){
	prop.put(filename, String.valueOf(offset));
}


/**
 *This method updates  a file(backup file) on register
 * @param filename The name of the file(backup file)
 * @param offset The offset of the file(backup file)
 */
public void update(String filename, long offset){
	prop.setProperty(filename, String.valueOf(offset));
}


/**
 * This method removes a file(backup file) from the register
 * @param filename The name of the file(backup file)
 */
public void remove(String filename){
	prop.remove(filename);
}


/**
 *
 * @param filename The name of the file(backup file)
 * @return
 */
public boolean exist(String filename){
	return prop.containsKey(filename);
}


/**
 *
 * @param filename The name of the register file(backup file)
 * @return The offset the file(backup file)
 * @throws java.lang.NumberFormatException
 */
public long getOffset(String filename) 
	throws NumberFormatException {

    long offset;

    try{

        offset = Long.parseLong(prop.getProperty(filename));
        if(offset < 0){
            prop.setProperty(filename, String.valueOf(0L));
            offset = 0L;
        }
    } catch(NumberFormatException e){
        prop.setProperty(filename, String.valueOf(0L));
        offset = 0L;
    }

    return offset;
}


/**
 * This method loads the register file
 * @param filename The name of the register file(backup file)
 * @throws java.io.IOException
 */
public void load(String filename)
throws IOException{

	FileReader file = null;

	try {
			file = new FileReader(filename);
			prop.load(file);
			file.close();
	} catch (IOException e) {
		try {
			if(file!=null){
    			file.close();
				file = null;
			}
		}catch (IOException e1) {}
		throw new IOException(e);
	}
}


/**
 * this method saves the register file
 * @param filename The name of the register file(backup file)
 * @throws java.io.IOException
 */
public void save(String filename)
throws IOException{
		FileWriter file = null;
		try {
			file = new FileWriter(filename);
			prop.store(file,null);
			file.close();
		} catch (IOException e) {
		try {
			if(file!=null){
				file.close();
				file = null;
			}
		}catch (IOException e1) {}
		throw new IOException(e);
	}
}


}
